<?php

declare(strict_types=1);

namespace owns\interface;

use Closure;
use owns\enum\SysEnum;
use think\facade\Cache;
use think\Request;
use think\Response;

/**
 * 中间件
 */
abstract class MiddlewareInterface
{
    /**
     * 处理请求
     * @param object $request
     * @param Closure $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $header = $request->header();
        if (isset($header['authorization'])) {
            $token = str_replace('Bearer ', '', $header['authorization']);
        } else {
            $token = '';
        }
        return $this->handleRequest($request, $token, $next);
    }
    /**
     * ip限流
     * @param object $request
     */
    public function ipLimiting($request)
    {
        $key = $request->ip() . '-' . $request->baseUrl();
        if ($num = Cache::get($key)) {
            if ($num > SysEnum::RATE_LIMITING) {
                tips('请求频繁');
            }
            Cache::inc($key);
        } else {
            Cache::set($key, 1, 3);
        }
    }
    /**
     * 处理请求数据
     * @param  Request $request
     * @param  string  $token
     * @param  Closure  $next
     */
    abstract public function handleRequest($request, $token, $next);
}
